package dbopr

import (
	"github.com/myesui/uuid"
	"myCloud/dbmodel"
	"myCloud/utils"
	"time"
)

type userTokenProvider struct{}

func NewUserTokenProvider() *userTokenProvider {
	return &userTokenProvider{}
}

func (*userTokenProvider) Get(token string) (*dbmodel.UserToken, bool, error) {
	var out dbmodel.UserToken
	query := dbSession.Where("token=? and stat='VALID'", token).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}

	return &out, false, query.Error
}

func newTokenUuid() string {
	return uuid.NewV1().String()
}

func (*userTokenProvider) New(userID uint, expire int) (*dbmodel.UserToken, error) {
	now := time.Now()
	expireTime := now.Add(time.Duration(expire) * time.Second)
	var r = &dbmodel.UserToken{
		UserID:  userID,
		Expire:  utils.Timetostr(expireTime),
		Refresh: newTokenUuid(),
		Token:   newTokenUuid(),
		Stat:    "VALID",
	}
	err := dbSession.Create(r).Error
	return r, err
}

func (*userTokenProvider) LogoutToken(tokenID uint) error {
	token := &dbmodel.UserToken{}
	token.ID = tokenID

	return dbSession.Delete(token).Error
}

func (*userTokenProvider) LogoutUser(userID uint) error {
	return dbSession.Delete(dbmodel.UserToken{}, "user_id=?", userID).Error
}
